//
//  MineInfoViewController.m
//  duoduo
//
//  Created by wanghao on 16/11/7.
//  Copyright © 2016年 LX. All rights reserved.
//

#import "MineInfoViewController.h"
#import "CheckViewController.h"
#import "HYPersonModel.h"
#import "MHUploadParam.h"

@interface MineInfoViewController ()<UIActionSheetDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIButton *submitBtn;

@end

@implementation MineInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    self.title = @"个人资料";
    self.view.backgroundColor = LXHexColor(0xF5F6F7);
    //登录按钮
    _submitBtn.backgroundColor = LXHexColor(0x5DCA68);
    _submitBtn.layer.cornerRadius = 6;
    _submitBtn.layer.masksToBounds = YES;

    _headImageBtn.layer.cornerRadius = 25;
    _headImageBtn.layer.masksToBounds = YES;

    _nameField.delegate = self;

    [self getUserInfo];

    [self setupForDismissKeyboard];
}
- (void)getUserInfo{
    NSDictionary *dic = @{@"uid":appD.userId};
    __weak typeof(self) weakSelf = self;
    [MHNetworkManager postReqeustWithURL:URL(@"?m=appface&c=user&a=info") params:dic successBlock:^(NSDictionary *returnData) {
        NSLog(@"returnData = %@",returnData);
        if (ResultJudge) {
            HYPersonModel *model = [[HYPersonModel alloc] init];
            [model setValuesForKeysWithDictionary:returnData[@"data"]];
            [[TMCache sharedCache] setObject:model forKey:@"userModel"];
            [[TMCache sharedCache] setObject:model.uid forKey:@"userId"];

            [weakSelf markUI];
        }else{
            ShowResultMsg;
        }
    } failureBlock:^(NSError *error) {
        DTLog(@"error = %@",error);
        ShowFailMsg;
    } showHUD:YES];
}
- (void)markUI
{
    HYPersonModel *model = appD.userModel;
    [_headImageBtn sd_setImageWithURL:[NSURL URLWithString:model.face] forState:UIControlStateNormal placeholderImage:NoHeadImage];
    _nameField.text = model.username;
    NSString *sexStr = [model.sex isEqualToString:@"1"]?@"男":@"女";
    [_sexBtn setTitle:sexStr forState:UIControlStateNormal];
    _phoneLabel.text = model.mobile;
}
- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden=YES;
}
- (IBAction)toCheckClick:(id)sender {
    CheckViewController * check = [[CheckViewController alloc]init];
    [self.navigationController pushViewController:check animated:YES];
}
- (IBAction)updateHeadImage:(id)sender {
    [self updateImageFromCameraOrPhotoLibrary];
}

- (IBAction)updateSex:(id)sender {
    UIActionSheet *actionsheeter = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"男",@"女",nil];
    [actionsheeter setActionSheetStyle:UIActionSheetStyleBlackOpaque];
    [actionsheeter showInView:self.view];
}
//修改个人信息
- (void)updateUseMsgWithKey:(NSString *)key andValue:(NSString *)value
{
    [MHNetworkManager postReqeustWithURL:URL(@"?m=appface&c=user&a=upinfo") params:@{@"uid":appD.userId,key:value} successBlock:^(NSDictionary *returnData) {
        NSLog(@"returnData = %@",returnData);
        if (ResultJudge) {
            HYPersonModel *model = appD.userModel;
            if ([key isEqualToString:@"face"]) {
                ShowSomeMsg(@"保存头像成功");
                model.face = value;
                [_headImageBtn sd_setImageWithURL:[NSURL URLWithString:value] forState:UIControlStateNormal placeholderImage:NoHeadImage];
            }else if ([key isEqualToString:@"username"]){
                ShowSomeMsg(@"保存姓名成功");
                model.username = value;
                _nameField.text = value;
            }else if ([key isEqualToString:@"sex"]){
                ShowSomeMsg(@"保存性别成功");
                model.sex = value;
                [_sexBtn setTitle:[value isEqualToString:@"1"]?@"男":@"女" forState:UIControlStateNormal];
            }
            [[TMCache sharedCache] setObject:model forKey:@"userModel"];
        }else{
            ShowResultMsg;
        }
    } failureBlock:^(NSError *error) {
        DTLog(@"error = %@",error);
        ShowFailMsg;
    } showHUD:YES];
}
#pragma mark-UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image= [info objectForKey:@"UIImagePickerControllerEditedImage"];

    NSData *imageData = UIImageJPEGRepresentation(image,0.5);

    __weak typeof(self) weakSelf = self;
    [self dismissViewControllerAnimated:YES completion:^{
        NSDictionary *dic =@{@"upfile_token":@"WfLM7fyAMBfML8",@"pic":imageData};
        MHUploadParam *upload = [[MHUploadParam alloc] init];
        upload.data           = imageData;
        upload.name = @"pic";
        upload.mimeType = @"image/jpeg";

        [MHNetworkManager uploadFileWithURL:URL(@"?m=appface&c=pic&a=up") params:dic successBlock:^(NSDictionary *returnData) {
            NSLog(@"returnData = %@",returnData);
            if (ResultJudge) {
                NSString *path = returnData[@"data"][@"pic_url"];

                [weakSelf updateUseMsgWithKey:@"face" andValue:path];
            }else{
                ShowResultMsg;
            }
        } failureBlock:^(NSError *error) {
            NSLog(@"error == %@",error);
            ShowSomeMsg(@"上传头像失败");
        } uploadParam:upload showHUD:YES];
    }];
}
#pragma mark - ActionSheeet Delegate Methods
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{

    NSString *sexStr;
    switch (buttonIndex) {
        case 0:{
            sexStr = @"1";
        }
            break;
        case 1:{
            sexStr = @"0";
        }
            break;
        default:

            break;
    }

    [self updateUseMsgWithKey:@"sex" andValue:sexStr];
}
#pragma mark textfieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self updateUseMsgWithKey:@"username" andValue:textField.text];
}
@end
